﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using Core.BOL;
using Core.DAL;
using Core.Extentions;
using Elmah;

namespace Core.ScheduleTask
{
    internal static class ClearDatas
    {
        internal static void ClearOldZipFiles(string appPath)
        {
            try
            {
                string tempFolder = ConfigurationManager.AppSettings["TempPath"];
                tempFolder = appPath + tempFolder;
                string[] files = Directory.GetFiles(tempFolder, "*.zip");

                foreach (var file in files)
                {
                    FileInfo fi = new FileInfo(file);
                    if (fi.CreationTime < DateTime.Now.AddDays(-14))
                    {
                        fi.Delete();
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorLog.GetDefault(null).Log(new Error(ex));
            }
        }

        internal static void ClearStatMail()
        {
            StatViewsRepository svr = null;
            StatMailsRepository smr = null;
            MailToGenerateRepository mtg = null;

            try
            {
                svr = new StatViewsRepository();
                smr = new StatMailsRepository();
                mtg = new MailToGenerateRepository();

                List<vw_Mail_MailsView> mailViews = smr.SelectMailViews();
                mailViews = mailViews.Where(p => p.InsertDate <= DateTime.Now.GetNowTimeByTimeZone().AddMonths(-3)).ToList();

                foreach (vw_Mail_MailsView mailView in mailViews)
                {
                    svr.DeleteViews(mailView.ID);
                    svr.Save();
                    smr.DeleteMailStat(mailView.ID);
                    smr.Save();
                }
            }
            catch(Exception ex)
            {
                ErrorLog.GetDefault(null).Log(new Error(ex));
            }
            finally
            {
                if (mtg != null)
                {
                    mtg.Dispose();
                }

                if (svr != null)
                {
                    svr.Dispose();
                }

                if (smr != null)
                {
                    smr.Dispose();
                }
            }
            
        }
    }
}
